package inet.app.view.dialog;

import inet.app.R;
import inet.app.common.OnLoginListener;
import inet.app.common.XoSoConstants;
import inet.app.controller.connect.JsonParser;
import inet.app.controller.parser.Parser_Member;
import inet.app.controller.request.Request;
import inet.app.model.object.Member;
import inet.app.model.util.AsyncTaskExecutor;
import inet.app.model.util.MyPreferenceManager;
import inet.app.model.util.NetworkUtil;
import inet.app.model.util.SmartLog;
import inet.app.model.util.StringUtil;
import inet.app.view.activity.MyApp;
import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginDialog extends DialogFragment {

	private EditText mUsernameEdt;
	private EditText mPassEdt;
	private TextView mErrorText;

	private Context mContext;
	private String mUsername;
	private String mPassword;
	private OnLoginListener mLoginListener;
	AsyncTask<Void, Void, String> mLoginTask;

	public LoginDialog(Context context) {
		this.mContext = context;
	}

	public static LoginDialog newInstance(Context context) {
		LoginDialog loginDialog = new LoginDialog(context);
		return loginDialog;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		Dialog dialog = new Dialog(mContext, android.R.style.Theme_Dialog);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
		dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
		View view = LayoutInflater.from(mContext).inflate(R.layout.view_login,null);
		dialog.setContentView(view);
		dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,R.drawable.icon_login);
		dialog.getWindow().setTitleColor(XoSoConstants.Yellow1);
		dialog.setTitle("Đăng Nhập");

		
		mUsernameEdt = (EditText) view.findViewById(R.id.username_edt);
		mPassEdt = (EditText) view.findViewById(R.id.password_edt);
		mErrorText = (TextView) view.findViewById(R.id.error_tv);

		view.findViewById(R.id.login_button).setOnClickListener(
				mLoginClickListener);
		view.findViewById(R.id.register_button).setOnClickListener(
				mRegisterListener);
//		view.findViewById(R.id.forget_pass_tv).setOnClickListener(
//				mForgetPassListener);
		

		return dialog;
	}

	View.OnClickListener mLoginClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			login();
		}
	};

	View.OnClickListener mRegisterListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			LoginDialog.this.dismiss();
			RegisterDialog.newInstance(mContext)
					.setLoginListener(mLoginListener)
					.show(getFragmentManager(), "register_dialog");
		}
	};

	View.OnClickListener mForgetPassListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			LoginDialog.this.dismiss();
			ForgetPassDialog.newInstance(mContext).show(getFragmentManager(),
					"forget_dialog");
		}
	};

	public LoginDialog setLoginListener(OnLoginListener loginListener) {
		this.mLoginListener = loginListener;
		return this;
	}

	private void login() {

		mUsername = mUsernameEdt.getText().toString();
		mPassword = mPassEdt.getText().toString();
		boolean isValid = validate();
		if (isValid) {
			implementLogin();
		}
	}

	private boolean validate() {

		String mError = "";
		if (TextUtils.isEmpty(mUsername)) {
			mError = "Điền tên đăng nhập";
		} else if (!StringUtil.validateUserName(mUsername)) {
			mError = "Tên đăng nhập không hợp lệ";
		} else if (TextUtils.isEmpty(mPassword)) {
			mError = "Điền mật khẩu";
		} else if (mPassword.length() < 8) {
			mError = "Mật khẩu không hợp lệ ( >= 8 kí tự )";
		}
		if (!TextUtils.isEmpty(mError)) {
			mErrorText.setVisibility(View.VISIBLE);
			mErrorText.setText(mError);
			return false;
		} else {
			mErrorText.setVisibility(View.GONE);
			return true;
		}
	}

	private void implementLogin() {
		// check network
		if (!NetworkUtil.getInstance(mContext).isConnect()) {
			Toast.makeText(mContext,
					mContext.getString(R.string.error_connect),
					Toast.LENGTH_LONG).show();
			this.dismiss();
			return;
		}
		
		if(mLoginTask != null) {
			return;
		}
		
		mLoginTask = new AsyncTask<Void, Void, String>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				if (mLoginListener != null) {
					mLoginListener.onStart();
				}
			}

			@Override
			protected String doInBackground(Void... params) {
				String result = null;
				JsonParser jParser = new JsonParser();
				Request request = new Request();
				String loginUrl = request.getLogin(mUsername, mPassword);
				if (TextUtils.isEmpty(loginUrl)) {
					return null;
				}
				result = jParser.getURL(request.getLogin(mUsername, mPassword));
				return result;
			}

			@Override
			protected void onPostExecute(String result) {
				SmartLog.d(result);
				mLoginTask = null;
				if (result == null) {
					if (mLoginListener != null) {
						mLoginListener.onFinish();
					}
					showToast(R.string.loi_dang_nhap_tu_server);
					LoginDialog.this.dismiss();
				} else if (result.startsWith("0")) {
					if (mLoginListener != null) {
						mLoginListener.onFinish();
					}
					showToast(R.string.sai_ten_dang_nhap_hoac_mat_khau);
				} else {

					Member member = Parser_Member.getMember(result);

					if (member == null) {
						// can't convert
						showToast(R.string.loi_dang_nhap_tu_server);
						if (mLoginListener != null) {
							mLoginListener.onFinish();
						}
						LoginDialog.this.dismiss();
						return;
					}

					//login success, save member to preference
					MyPreferenceManager.getInstance(mContext).setMember(member);
					showToast(R.string.dang_nhap_thanh_cong);
					if (mLoginListener != null) {
						mLoginListener.onFinish();
//						((MyApp) getActivity().getApplication()).setMSISDN(mUsername);
						MyApp.MSISDN= mUsername;
					}
					LoginDialog.this.dismiss();
				}

			}
		};
//		mLoginTask.executeOnExecutor(Util.creatForceAsyncTaskThreadPool());
		AsyncTaskExecutor.executeConcurrently(mLoginTask);
	}

	private void showToast(int resId) {
		Toast.makeText(mContext, mContext.getString(resId), Toast.LENGTH_LONG)
				.show();
	}
	
	@Override
	public void onStop() {
		super.onStop();
		if(mLoginTask != null) {
			SmartLog.e("cancel login task");
			mLoginTask.cancel(true);
			mLoginTask = null;
		}
	}
	
}
